# -*- coding: utf-8 -*-
import gobject
import gtk
from gtk import gdk

import imageutil

class TileSetViewer(gtk.DrawingArea):
    """
    """

    def __init__(self, tile_set, tiles_per_row=5):
        super(TileSetViewer, self).__init__()
        self.tiles_per_row = tiles_per_row
        self.set_events(gtk.gdk.EXPOSURE_MASK)

        num_rows = tile_set.num_tiles / self.tiles_per_row
        self.set_size_request(self.tiles_per_row * tile_set.tile_width,
                              (num_rows + 1) * tile_set.tile_width)


        self.tile_set = tile_set

    def do_expose_event(self, event):
        self._draw_tiles(self.window)

    def _draw_tiles(self, drawable):
        gc = self.get_style().fg_gc[gtk.STATE_NORMAL]

        x, y = 0, 0
        for i, pb in enumerate(self.tile_set):
            drawable.draw_pixbuf(gc, pb, 0,0, x,y)
            if (i+1) % self.tiles_per_row == 0:
                x = 0
                y += self.tile_set.tile_height
            else:
                x += self.tile_set.tile_width

gobject.type_register(TileSetViewer)


class TileSetPallete(TileSetViewer):
    def __init__(self, tile_set):
        super(TileSetPallete, self).__init__(tile_set)

        self.add_events(gtk.gdk.BUTTON_PRESS_MASK)
        self.selected = (0,0)

    def do_expose_event(self, event):
        super(TileSetPallete, self).do_expose_event(event)
        self._draw_cursor(self.window)

    def do_button_press_event(self, event):
        xtile = int(event.x / self.tile_set.tile_width)
        ytile = int(event.y / self.tile_set.tile_height)

        i = self._index(xtile, ytile)

        if xtile < self.tiles_per_row and i < self.tile_set.num_tiles:
            self.selected = xtile, ytile
            self.queue_draw()

    def get_selected_index(self):
        return self._index(*self.selected)

    def _index(self, xtile, ytile):
        return ytile * self.tiles_per_row + xtile

    def _draw_cursor(self, drawable):
        cr = drawable.cairo_create()

        w, h = self.tile_set.tile_width, self.tile_set.tile_height
        x = self.selected[0] * w
        y = self.selected[1] * h

        cr.set_source_rgba(1.0, 1.0, 0.0, 0.6)
        cr.rectangle(x,y,w,h)
        cr.stroke()

gobject.type_register(TileSetPallete)


# class TileLayerView(gtk.DrawingArea):
#     """Gtk Viewer for a tile layer.
#     """

#     def __init__(self, tilelayer):
#         """
# 	"""
#         super(TileLayerView, self).__init__()
#         # self.set_events(gtk.gdk.EXPOSURE_MASK)

#         self.tilelayer = tilelayer
#         self.set_size_request(self.tilelayer.width,
#                               self.tilelayer.height)

#     def do_expose_event(self, event):
#         """Draws the tile layer.
#         """
#         a = event.area
#         region = a.x, a.y, a.width, a.height

#         gc = self.get_style().fg_gc[gtk.STATE_NORMAL]
#         window = self.window

#         for ((x,y), data) in self.tilelayer.get_cells(region):
#             if data:
#                 pb = imageutil.pil_to_pixbuf(data)
#                 window.draw_pixbuf(gc, pb, 0,0, x,y)

# gobject.type_register(TileLayerView)


# class TileLayerEditor(TileLayerView):
#     """Tile layer editor
#     """

#     def __init__(self, tilelayer, tilepallete):
#         """Creates an editor for the given layer and uses the given
#         tilepallete as data source for edits.
# 	"""
#         super(TileLayerEditor, self).__init__(tilelayer)
#         self.add_events(gtk.gdk.BUTTON_PRESS_MASK)
#         self.tilepallete = tilepallete

#     def do_button_press_event(self, event):
#         """Handle mouse clicks.
#         """
#         value = self.tilepallete.get_selected_index()
#         self.tilelayer.set_data((event.x, event.y), value)
#         self.queue_draw()

# gobject.type_register(TileLayerEditor)


if __name__ == '__main__':
    import unittest
    from PIL import Image
    import tileimage
    import tileset


    def stub_window(widget, w=300, h=300):
        window =  gtk.Window()
        window.set_default_size(w, h)
        window.set_title(widget.__class__.__name__)
        window.connect('delete-event', gtk.main_quit)
        scrolled_window = gtk.ScrolledWindow()
        window.add(scrolled_window)
        scrolled_window.add_with_viewport(widget)
        window.show_all()


    class TestTileWidgets(unittest.TestCase):
        def setUp(self):
            self.tileset = tileset.from_image("hills", "hills.png", 32)

        def test_pallete(self):
            widget = TileSetPallete(self.tileset)
            stub_window(widget)
            gtk.main()

        def test_viewer(self):
            widget = TileSetViewer(self.tileset)
            stub_window(widget)
            gtk.main()

        # def test_tile_layer_viewer(self):
        #     from layer import TileLayer
        #     layer = TileLayer("testlayer", 100,100,self.tileset)

        #     for x in range(100):
        #         for y in range(100):
        #             layer._data[x][y] = 1

        #     widget = TileLayerView(layer)
        #     stub_window(widget)
        #     gtk.main()


    unittest.main()
